package com.example.aijie.autoreadhelper.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.aijie.autoreadhelper.R;
import com.example.aijie.autoreadhelper.activity.SetActivity;
import com.example.aijie.autoreadhelper.appbean.BaseAppBean;
import com.example.aijie.autoreadhelper.constant.AppConstant;
import com.example.aijie.autoreadhelper.utils.AppUtils;
import com.example.aijie.autoreadhelper.utils.LogUtils;
import com.example.aijie.autoreadhelper.utils.PermissionHelper;
import com.example.aijie.autoreadhelper.utils.RoomUtils;
import com.example.aijie.autoreadhelper.widget.DraggableFloatView;

import org.litepal.LitePal;

import java.util.List;
import java.util.Random;

/**
 * 自动阅读新闻的服务
 */
public class AutoReadService extends Service {
    private static final int WHAT_TO_HOME = 1;  // 到home桌面
    private static final int WHAT_BACK = 2;  // 返回
    private static final int WHAT_ARTICLE_SCROLL_DOWN = 3;  // 文章详情向下滚动
    private static final int WHAT_LIST_SCROLL_DOWN = 4;  // 文章列表向下滚动
    private static final int WHAT_ARTICLE_SCROLL_UP = 5;  // 向上滚动
    private static final int WHAT_LIST_SCROLL_UP = 6;  // 向上滚动
    private static final int WHAT_LIST_CLICK = 7;  // 点击文章列表
    private static final int WHAT_START_APP = 8;  // 启动app
    private static final int WHAT_NEXT_ARTICLE = 9;  // 看下一个文章

    private DraggableFloatView floatView;
    private ImageView iv_control;
    private TextView tv_desc;

    public static BaseAppBean appBean;  // 正在运行的app信息

    private MyHandler myHandler = new MyHandler();

    private int currentPageTime = 0;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (PermissionHelper.hasOverlay(this)) {
            initWindow();//设置窗口的参数
        }
    }

    /**
     * 初始化windowManager
     */
    private void initWindow() {
        LayoutInflater inflater = LayoutInflater.from(getApplication());
        View mLayout = inflater.inflate(R.layout.floating_window, null);
        iv_control = (ImageView) mLayout.findViewById(R.id.iv_control);
        tv_desc = (TextView) mLayout.findViewById(R.id.tv_desc);
        mLayout.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopSelf();
            }
        });
        mLayout.findViewById(R.id.iv_setting).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 设置
                startActivity(new Intent(AutoReadService.this, SetActivity.class));
            }
        });
        floatView = new DraggableFloatView(this, null);
        iv_control.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (appBean == null) {
                    iv_control.setImageResource(R.drawable.icon_stop);
                    randomStartApp();
                } else {
                    myHandler.removeCallbacksAndMessages(null);
                    appBean = null;
                    iv_control.setImageResource(R.drawable.icon_start);
                }
            }
        });
        floatView.setView(mLayout);
        floatView.show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        dealStartCommand(intent);
        return super.onStartCommand(intent, flags, startId);
    }

    private void dealStartCommand(Intent intent) {
        if (appBean == null) {
            randomStartApp();
        } else {
            String fromEvent = intent.getStringExtra(KEY_FROM_EVENT);
            if (!TextUtils.isEmpty(fromEvent)) {
                switch (fromEvent) {
                    case FROM_EVENT.Event_start_read_article:  // 文章详情页，开始阅读
                        currentPageTime = 0;
                        myHandler.removeCallbacksAndMessages(null);
                        myHandler.sendEmptyMessageDelayed(WHAT_ARTICLE_SCROLL_DOWN, 1500);
                        break;
                    case FROM_EVENT.Event_end_adv_and_re_read:  // 广告页面，返回重新阅读
                        myHandler.removeCallbacksAndMessages(null);
                        myHandler.sendEmptyMessage(WHAT_NEXT_ARTICLE);
                        break;
                    case FROM_EVENT.Event_start_choose_item_and_read:  // 文章列表页面，开始阅读
                        myHandler.removeCallbacksAndMessages(null);
                        myHandler.sendEmptyMessage(WHAT_NEXT_ARTICLE);
                        break;
                }
            }
        }
    }

    private void randomStartApp() {
        AppUtils.goHome(this);
        List<BaseAppBean> appBeanList = LitePal.where("enableToday = 0").find(BaseAppBean.class);
        if (appBeanList != null && appBeanList.size() > 0) {
            appBean = appBeanList.get(new Random().nextInt(appBeanList.size()));
            log("app信息：" + appBean);
            if (appBean != null) {
                if (tv_desc != null) {
                    tv_desc.setText(appBean.getAppName());
                }
                iv_control.setImageResource(R.drawable.icon_stop);
                Message message = Message.obtain();
                message.what = WHAT_START_APP;
                message.obj = appBean;
                myHandler.sendMessage(message);
            }
        }
    }

    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHAT_TO_HOME:
                    log("到桌面");
                    AppUtils.goHome(AutoReadService.this);
                    break;
                case WHAT_BACK:
                    log("点击返回");
                    currentPageTime = 0;
                    RoomUtils.performBack();
                    break;
                case WHAT_ARTICLE_SCROLL_DOWN:
                    if (currentPageTime >= getArticleReadTime()) {
                        currentPageTime = 0;
                        myHandler.sendEmptyMessage(WHAT_NEXT_ARTICLE);
                        return;
                    }
                    currentPageTime++;
                    log("向下滚动: " + currentPageTime);
                    RoomUtils.performArticleScrollDown();
                    myHandler.sendEmptyMessageDelayed(WHAT_ARTICLE_SCROLL_DOWN, 1500);
                    break;
                case WHAT_ARTICLE_SCROLL_UP:
                    log("向上滚动");
                    RoomUtils.performArticleScrollUp();
                    break;
                case WHAT_LIST_CLICK:
                    log("点击条目");
                    currentPageTime = 0;
                    RoomUtils.performClick();
                    myHandler.sendEmptyMessageDelayed(WHAT_ARTICLE_SCROLL_DOWN, 3000);
                    break;
                case WHAT_START_APP:
                    log("启动app");
                    BaseAppBean appBean = (BaseAppBean) msg.obj;
                    if (appBean != null) {
                        AppUtils.startApp(AutoReadService.this, appBean.getPackageName(), appBean.getStartClassName());
                    }
                    myHandler.sendEmptyMessageDelayed(WHAT_LIST_CLICK, 12000);
                    break;
                case WHAT_NEXT_ARTICLE:  // 下一篇文章
                    log("下一篇文章");
                    currentPageTime = 0;
                    myHandler.sendEmptyMessage(WHAT_BACK);
                    myHandler.sendEmptyMessageDelayed(WHAT_LIST_SCROLL_DOWN, 1500);
                    myHandler.sendEmptyMessageDelayed(WHAT_LIST_CLICK, 3000);
                    break;
                case WHAT_LIST_SCROLL_DOWN:
                    log("列表向下滚动");
                    RoomUtils.performListScrollDown();
                    break;
                case WHAT_LIST_SCROLL_UP:
                    log("列表向上滚动");
                    RoomUtils.performListScrollUp();
                    break;
            }
        }
    }

    private void log(String message) {
        LogUtils.i(message);
    }

    private int getArticleReadTime() {
        if (appBean != null) {
            return appBean.getArticleReadTime();
        }
        return AppConstant.PER_ARTICLE_READ_SECOND;
    }


    @Override
    public void onDestroy() {
        if (myHandler != null) {
            myHandler.removeCallbacksAndMessages(null);
        }
        if (floatView != null) {
            floatView.dismiss();
        }
        appBean = null;
        log("服务销毁了");
        super.onDestroy();
    }

    public static final String KEY_FROM_EVENT = "key_from_event";

    public interface FROM_EVENT {
        String Event_start_read_article = "1";  // 开始阅读文章
        String Event_end_adv_and_re_read = "2";  // 是广告，返回列表页面，重新点击开始阅读
        String Event_start_choose_item_and_read = "3";  // 到了列表页面，开始选择条目阅读
    }
}
